package com.test.util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author lizhilong
 * @create 2019/11/15 14:14
 * @desc
 */
public class DownloadUtil {

    public static String download(String imageUrl,String fileName ,String savePath) {
        //获取文件名，文件名实际上在URL中可以找到
        //String fileName = imageUrl.substring(imageUrl.lastIndexOf("/"), imageUrl.length());
        //这里服务器上要将此图保存的路径
        DataOutputStream out = null;
        DataInputStream in = null;
        HttpURLConnection connection = null;
        try {
            /*将网络资源地址传给,即赋值给url*/
            URL url = new URL(imageUrl);
            /*此为联系获得网络资源的固定格式用法，以便后面的in变量获得url截取网络资源的输入流*/
            connection = (HttpURLConnection) url.openConnection();
            in = new DataInputStream(connection.getInputStream());
            /*此处也可用BufferedInputStream与BufferedOutputStream*/
            out = new DataOutputStream(new FileOutputStream(savePath + fileName));
            /*将参数savePath，即将截取的图片的存储在本地地址赋值给out输出流所指定的地址*/
            byte[] buffer = new byte[4096];
            int count = 0;
            /*将输入流以字节的形式读取并写入buffer中*/
            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
            //返回内容是保存后的完整的URL
            return savePath + fileName;

        } catch (Exception e) {
            return null;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {

                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {

                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }


    public static void main(String[] args){
        System.out.println(System.currentTimeMillis());
       // download("https://img.alicdn.com/bao/uploaded/i1/3392960944/O1CN01bLKnVe1IqOSQROPut_!!3392960944.jpg");
        System.out.println(System.currentTimeMillis());
    }
}
